﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using DataAcquisition.TransferObjects;
using System.Threading;

namespace DataAcquisition
{
    public delegate void ProcessEegData(EegData eegData);

    public class EegReceiver
    {
        private TcpAcquirer tcpAcquirer;

        public ProcessEegData ProcessEegData;

        public BasicInfo BasicInfo { get; private set; }

        public EegReceiver()
        {
            IDataReceiver dataReceiver = new DataReceiver(this);
            tcpAcquirer = new TcpAcquirer(dataReceiver);
        }

        public void StartReceiving()
        {
            tcpAcquirer.Start(Connection.GetServerName(), Connection.GetPortNumber());

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += DoWork;    
            worker.RunWorkerAsync();
        }

        public void StopReceiving()
        {
            tcpAcquirer.Stop();
        }

        private void DoWork(object sende, DoWorkEventArgs ergs)
        {
            while (tcpAcquirer.IsActive)
            {
                if (tcpAcquirer.HasEegData)
                {
                    EegData eegData = tcpAcquirer.GetEegData();
                    ProcessEegData(eegData);
                }
                else
                {
                    Thread.Sleep(20);
                }
            }
        }       

        private class DataReceiver : DummyDataReceiver
        {
            private readonly EegReceiver receiver;

            public DataReceiver(EegReceiver receiver)
            {
                this.receiver = receiver;
            }

            public override void ProcessBasicInfo(BasicInfo basicInfo)
            {
                this.receiver.BasicInfo = basicInfo;
            }
        }
    }

}
